package com.fwmagic.webmagic;

import com.fwmagic.webmagic.utils.CatchImage;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 爬取图片地址（csdn）
 */
public class ImageProcessor implements PageProcessor {

    private Site site = Site.me().setDomain("http://www.tooopen.com/").setRetryTimes(3).setCharset("UTF-8").setSleepTime(1000);

    //详情页表达式
    private static final String URL_PATTERN = "http://www\\.tooopen\\.com/view/\\d+";

    private final AtomicLong count = new AtomicLong(0);

    @Override
    public void process(Page page) {
        //取详情页数据
        if(page.getUrl().regex(URL_PATTERN).match()){
            page.putField("title",page.getHtml().xpath("//div[@class='con-box']/h1/text()"));
            if(page.getResultItems().get("title")==null){
                page.setSkip(true);
            }else{
                page.putField("img",page.getHtml().xpath("//div[@class='pic-box']/img/@src"));
                count.incrementAndGet();//+1
                List<String> imgSrc = new ArrayList<String>();
                imgSrc.add(String.valueOf(page.getResultItems().get("img")));
                CatchImage cm = new CatchImage();
                cm.getImageSrc(imgSrc);
                //下载图片
                cm.Download(imgSrc);
                System.out.println("==========【兴趣e族】共抓取到"+count+"条有效数据============");
            }
        }else{
            //发现详情页
            page.addTargetRequests(page.getHtml().links().regex(".*/view/\\d+\\.html").all());
            //发现下一页
            page.addTargetRequests(page.getHtml().css("div#papelist").links().regex(".*/img/87_312_1_\\d+.aspx").all());
        }
    }

    @Override
    public Site getSite() {
        return site;
    }

    public static void main(String[] args) {
        Spider.create(new ImageProcessor()).addUrl("http://www.tooopen.com/img/87_312_1_1.aspx").thread(3).run();
    }
}
